package com.ll.daipao.service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import com.ll.daipao.config.MainConfiguration;
import com.ll.daipao.dao.TAccountMapper;
import com.ll.daipao.dao.TSchoolMapper;
import com.ll.daipao.handler.*;
import com.ll.daipao.vo.City;
import com.ll.daipao.vo.TAccount;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceApacheHttpClientImpl;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.constant.WxMpEventConstants;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfOnlineList;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

import static me.chanjar.weixin.common.api.WxConsts.*;

/**
 * 
 * @author Binary Wang
 *
 */
@Service
public class CoreService {
  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @Autowired
  TSchoolMapper tSchoolMapper;

  @Autowired
  private TAccountMapper tAccountMapper;

    @Resource(name = "wxMpService")
    protected WxMpService wxMpService;
    @Autowired
    protected LogHandler logHandler;
    @Autowired
    protected SubscribeHandler subscribeHandler;
    @Autowired
    protected MsgHandler msgHandler;
    private WxMpMessageRouter router;

    @PostConstruct
    public void init() {
        this.refreshRouter();
    }

    public void requestGet(String urlWithParams) throws IOException {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpGet httpget = new HttpGet(urlWithParams);
        httpget.addHeader("Content-Type", "text/html;charset=UTF-8");
        //配置请求的超时设置
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(50)
                .setConnectTimeout(50)
                .setSocketTimeout(50).build();
        httpget.setConfig(requestConfig);

        CloseableHttpResponse response = httpclient.execute(httpget);
        System.out.println("StatusCode -> " + response.getStatusLine().getStatusCode());

        HttpEntity entity = response.getEntity();
        String jsonStr = EntityUtils.toString(entity);
        System.out.println(jsonStr);

        httpget.releaseConnection();
    }

    public void requestPost(String url, List<NameValuePair> params) throws ClientProtocolException, IOException {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();

        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

        CloseableHttpResponse response = httpclient.execute(httppost);
        System.out.println(response.toString());

        HttpEntity entity = response.getEntity();
        String jsonStr = EntityUtils.toString(entity, "utf-8");
        System.out.println(jsonStr);

        httppost.releaseConnection();
    }

    public void refreshRouter() {
        final WxMpMessageRouter newRouter = new WxMpMessageRouter(
                this.wxMpService);
        // 记录所有事件的日志
        newRouter.rule().handler(this.logHandler).next();
        // 关注事件
        newRouter.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT)
                .event(WxConsts.EventType.SUBSCRIBE).handler(this.subscribeHandler)
                .end();
        // 默认,转发消息给客服人员
        newRouter.rule().async(false).handler(this.msgHandler).end();
        this.router = newRouter;
    }

    public WxMpXmlOutMessage route(WxMpXmlMessage inMessage) {
        try {
            return this.router.route(inMessage);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        return null;
    }

    public WxMpUser getUserInfo(String openid, String lang) {
        WxMpUser wxMpUser = null;
        try {
            wxMpUser = this.wxMpService.getUserService().userInfo(openid, lang);
        } catch (WxErrorException e) {
            this.logger.error(e.getError().toString());
        }
        return wxMpUser;
    }


    public List<City> allSchool(){
        List<Map<String, Object>> maps = tSchoolMapper.selectAllSchool();
        Map<String,City> tempmap = new HashMap<String,City>();
        for (Map map : maps){
            String str = String.valueOf(map.get("city_id"));
            City city = null;
            List<Map<String,Object>> schools = new ArrayList<>();
            if(tempmap.containsKey(str)){
                city =tempmap.get(str);
                schools = city.gettSchools();
                schools.add(map);
                city.settSchools(schools);
            }
            else {
                city = new City();
                city.setId(Integer.parseInt(str));
                city.setTitle(String.valueOf(map.get("TITLE")));
                schools.add(map);
                city.settSchools(schools);
                tempmap.put(str,city);
            }
        }
        List<City> res = new ArrayList<>();
        for (String str : tempmap.keySet()){
            res.add(tempmap.get(str));
        }
        return res;
    }

    public TAccount checkOpenId(String openId){
        TAccount tAccount = tAccountMapper.selectAccountByOpenId(openId);
        if(tAccount==null){
            tAccount = new TAccount();
            try {
                WxMpUser wxMpUser = wxMpService.getUserService().userInfo(openId);
                tAccount.setNickName(wxMpUser.getNickname());
                tAccount.setCreateTime(new Date());
                tAccount.setCreateBy("wx");
                tAccount.setOpenid(wxMpUser.getOpenId());
                tAccount.setHendimgurl(wxMpUser.getHeadImgUrl());
                tAccountMapper.insertSelective(tAccount);
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
        return tAccount;
    }

}
